import { reactive, ref } from 'vue'

export function useEmergency(){
  // SOS面板显示状态
  const sosVisible = ref(false)
  
  // 倒计时秒数
  const sosCountdown = ref(5)
  
  // 紧急联系人列表
  const emergencyContacts = reactive([
    { 
      id: 1, 
      name: '儿子', 
      phone: '13800138001', 
      icon: '👨',
      isPrimary: true,
      relation: '家人'
    },
    { 
      id: 2, 
      name: '女儿', 
      phone: '13900139002', 
      icon: '👩',
      isPrimary: false,
      relation: '家人'
    },
    { 
      id: 3, 
      name: '社区医生', 
      phone: '13600136003', 
      icon: '👨‍⚕️',
      isPrimary: false,
      relation: '医疗'
    }
  ])
  
  let countdownTimer = null
  let pressTimer = null
  
  // 打开SOS面板
  const handleSosOpen = () => {
    sosVisible.value = true
    
    // 重度触觉反馈
    if(uni.vibrateShort){
      try { 
        uni.vibrateShort({ type: 'heavy' })
        // 连续震动3次提示紧急状态
        setTimeout(() => uni.vibrateShort({ type: 'heavy' }), 200)
        setTimeout(() => uni.vibrateShort({ type: 'heavy' }), 400)
      } catch(e){}
    }
    
    // 开始倒计时
    startCountdown()
  }
  
  // 关闭SOS面板
  const handleSosClose = () => {
    clearTimers()
    sosVisible.value = false
    sosCountdown.value = 5
    
    // 轻触觉反馈
    if(uni.vibrateShort){
      try { uni.vibrateShort({ type: 'light' }) } catch(e){}
    }
  }
  
  // 开始倒计时
  const startCountdown = () => {
    clearTimers()
    sosCountdown.value = 5
    
    countdownTimer = setInterval(() => {
      if(sosCountdown.value <= 1){
        handleSosCall()
      } else {
        sosCountdown.value -= 1
        
        // 每秒触觉反馈
        if(uni.vibrateShort){
          try { uni.vibrateShort({ type: 'medium' }) } catch(e){}
        }
      }
    }, 1000)
  }
  
  // 立即拨打主要联系人
  const handleSosCall = () => {
    clearTimers()
    
    // 找到主要联系人
    const primaryContact = emergencyContacts.find(c => c.isPrimary) || emergencyContacts[0]
    
    if(primaryContact){
      // 触觉反馈
      if(uni.vibrateShort){
        try { uni.vibrateShort({ type: 'heavy' }) } catch(e){}
      }
      
      // 拨打电话
      uni.makePhoneCall({
        phoneNumber: primaryContact.phone,
        success: () => {
          console.log('拨打成功:', primaryContact.name)
        },
        fail: (err) => {
          console.error('拨打失败:', err)
          uni.showToast({ 
            title: '拨打失败，请重试', 
            icon: 'none' 
          })
        }
      })
      
      // 关闭面板
      sosVisible.value = false
      sosCountdown.value = 5
    }
  }
  
  // 拨打指定联系人
  const handleContactCall = (contact) => {
    clearTimers()
    
    // 触觉反馈
    if(uni.vibrateShort){
      try { uni.vibrateShort({ type: 'medium' }) } catch(e){}
    }
    
    uni.makePhoneCall({
      phoneNumber: contact.phone,
      success: () => {
        console.log('拨打成功:', contact.name)
      },
      fail: (err) => {
        console.error('拨打失败:', err)
        uni.showToast({ 
          title: '拨打失败，请重试', 
          icon: 'none' 
        })
      }
    })
    
    // 关闭面板
    sosVisible.value = false
    sosCountdown.value = 5
  }
  
  // 清理定时器
  const clearTimers = () => {
    if(countdownTimer){
      clearInterval(countdownTimer)
      countdownTimer = null
    }
    if(pressTimer){
      clearTimeout(pressTimer)
      pressTimer = null
    }
  }
  
  // 添加联系人
  const addContact = (contact) => {
    emergencyContacts.push({
      id: Date.now(),
      ...contact
    })
  }
  
  // 删除联系人
  const removeContact = (contactId) => {
    const index = emergencyContacts.findIndex(c => c.id === contactId)
    if(index > -1){
      emergencyContacts.splice(index, 1)
    }
  }
  
  // 设置主要联系人
  const setPrimaryContact = (contactId) => {
    emergencyContacts.forEach(c => {
      c.isPrimary = (c.id === contactId)
    })
  }
  
  // 清理资源
  const cleanup = () => {
    clearTimers()
  }
  
  return { 
    sosVisible, 
    sosCountdown, 
    emergencyContacts, 
    handleSosOpen, 
    handleSosClose, 
    handleSosCall, 
    handleContactCall,
    addContact,
    removeContact,
    setPrimaryContact,
    cleanup
  }
}

